package com.csu.tingtian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csu.tingtian.common.CommonResponse;
import com.csu.tingtian.entity.Fruit;
import com.csu.tingtian.entity.LegalFarm;
import com.csu.tingtian.entity.ProvideProduce;
import com.csu.tingtian.entity.Vegetable;
import com.csu.tingtian.persistence.FruitMapper;
import com.csu.tingtian.persistence.LegalFarmMapper;
import com.csu.tingtian.persistence.ProvideProduceMapper;
import com.csu.tingtian.persistence.VegetableMapper;
import com.csu.tingtian.service.FarmRentCommentService;
import com.csu.tingtian.service.ProduceCommentService;
import com.csu.tingtian.service.ProduceService;
import com.csu.tingtian.vo.BusinessProduce;
import com.csu.tingtian.vo.Produce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("produceService")
public class ProduceServiceImpl implements ProduceService {
    @Autowired
    private ProvideProduceMapper provideProduceMapper;
    @Autowired
    private LegalFarmMapper legalFarmMapper;
    @Autowired
    private FruitMapper fruitMapper;
    @Autowired
    private VegetableMapper vegetableMapper;
    @Autowired
    private ProduceCommentService produceCommentService;
    @Autowired
    private FarmRentCommentService farmRentCommentService;

    private ProvideProduce provideProduce = null;
    private LegalFarm legalFarm = null;
    private Fruit fruit = null;
    private Vegetable vegetable = null;




    //根据农产品的id，获取上架了这个产品的所有商家信息（农场名，商家用户名，产品价格，店铺评分，农场地址）
    @Override
    public CommonResponse<List<Produce>> getProduceById(String id) {
        //先判断id是蔬菜还是水果
        String type = "";
        if(id.startsWith("V"))
            type = "vegetableId";
        if(id.startsWith("F"))
            type = "fruitId";

        //再根据id 在provideproduce表中查找出所有卖这个产品的商家list
        QueryWrapper<ProvideProduce> queryWrapper1 = new QueryWrapper<>();
        List<ProvideProduce> provideProduceList = provideProduceMapper.selectList(queryWrapper1.eq(type,id));

        List<Produce> produceList = new ArrayList<>();

        //遍历所有买这个产品的商家list，然后根据farmName在legalFarm里面查，
        for (int i = 0; i < provideProduceList.size(); i++) {
            Produce produce = new Produce();

            //得到商家详情
            legalFarm = legalFarmMapper.selectById(provideProduceList.get(i).getFarmName());

            //填入produce对象
            produce.setFarmName(legalFarm.getFarmName());
            produce.setFarmAddress(legalFarm.getFarmAddress());
            produce.setUserName(legalFarm.getUserName());

            produce.setPrice(provideProduceList.get(i).getPrice());

            /*******这里还需要填上店铺评分*********/
            /****调用评论的service层代码*****/
            int produceStar = produceCommentService.averageStarLevel(provideProduceList.get(i).getFarmName());
            int farmStar = farmRentCommentService.averageStarLevel(provideProduceList.get(i).getFarmName());

            int totalAverage = (produceStar + farmStar)/2;

            produce.setImportance(totalAverage);


            //字段填完后，将produce对象放入produceList
            produceList.add(produce);
        }

        return CommonResponse.createForSuccess(produceList);
    }


    //根据farmName获取该农场详细信息
    @Override
    public CommonResponse<LegalFarm> getFarm(String farmName) {
        legalFarm = legalFarmMapper.selectById(farmName);
        return CommonResponse.createForSuccess(legalFarm);
    }

    //根据fruitId获取该水果详细信息
    @Override
    public CommonResponse<Fruit> getFruitById(String id) {
        fruit = fruitMapper.selectById(id);
        return CommonResponse.createForSuccess(fruit);
    }

    //根据vegetableId获取该蔬菜详细信息
    @Override
    public CommonResponse<Vegetable> getVegetableById(String id) {
        vegetable = vegetableMapper.selectById(id);
        return CommonResponse.createForSuccess(vegetable);
    }

    //获取所有水果
    @Override
    public CommonResponse<List<Fruit>> getAllFruit() {
        List<Fruit> list = fruitMapper.selectList(null);
        return CommonResponse.createForSuccess(list);
    }

    //获取所有蔬菜
    @Override
    public CommonResponse<List<Vegetable>> getAllVegetable() {
        List<Vegetable> list = vegetableMapper.selectList(null);
        return CommonResponse.createForSuccess(list);
    }

    //商家上架农产品，即插入一条记录到provideproduce表中,若上架的是已经存在的，那么更新价格
    @Override
    public CommonResponse<ProvideProduce> insertProvideProduce(String id, double price, String farmName) {
        provideProduce = new ProvideProduce();
        provideProduce.setFarmName(farmName);
        provideProduce.setPrice(price);
        QueryWrapper<ProvideProduce> queryWrapper = new QueryWrapper<>();
        int count = 0;
        //判断id是蔬菜还是水果
        if(id.startsWith("V")) {
            provideProduce.setVegetableId(id);
            count = provideProduceMapper.selectCount(queryWrapper.nested(i->i.eq("vegetableId",id).eq("farmName",farmName)));
            ProvideProduce vegetable = provideProduceMapper.selectOne(queryWrapper.nested(i->i.eq("vegetableId",id).eq("farmName",farmName)));
            //判断count是否大于0
            if(count>0) {
                //若大于0，说明已存在，则更新价格
                vegetable.setPrice(price);
                provideProduceMapper.update(vegetable,queryWrapper.nested(i->i.eq("vegetableId",id).eq("farmName",farmName)));
            }
            else
                //count为0，说明并未上架过这个，所以插入
                provideProduceMapper.insert(provideProduce);
        }
        if(id.startsWith("F")) {
            provideProduce.setFruitId(id);
            count = provideProduceMapper.selectCount(queryWrapper.nested(i->i.eq("fruitId",id).eq("farmName",farmName)));
            ProvideProduce fruit = provideProduceMapper.selectOne(queryWrapper.nested(i->i.eq("fruitId",id).eq("farmName",farmName)));
            //判断count是否大于0
            if(count>0) {
                //若大于0，说明已存在，则更新价格
                fruit.setPrice(price);
                provideProduceMapper.update(fruit,queryWrapper.nested(i->i.eq("fruitId",id).eq("farmName",farmName)));
            }
            else
                //count为0，说明并未上架过这个，所以插入
                provideProduceMapper.insert(provideProduce);
        }

        return CommonResponse.createForSuccess(provideProduce);
    }


    //商家下架农产品，即删除provideproduce表中的某条记录
    @Override
    public CommonResponse<String> deleteProvideProduce(String id, String farmName) {
        QueryWrapper<ProvideProduce> queryWrapper = new QueryWrapper<>();
        int m = -2;
        //先判断id是蔬菜还是水果
        if(id.startsWith("V"))
            m = provideProduceMapper.delete(queryWrapper.nested(i->i.eq("vegetableId",id).eq("farmName",farmName)));
        if(id.startsWith("F"))
            m = provideProduceMapper.delete(queryWrapper.nested(i->i.eq("fruitId",id).eq("farmName",farmName)));

        if(m>-1)
            return CommonResponse.createForSuccess("下架成功");
        else
            return CommonResponse.createForError("下架失败");
    }


    //根据farmName获取他上架的所有农产品（provideProduce）
    @Override
    public CommonResponse<List<BusinessProduce>> getBusinessAllProduce(String farmName) {
        //在provideProduce表中获取该商家的所有上架产品
        QueryWrapper<ProvideProduce> queryWrapper = new QueryWrapper<>();
        List<ProvideProduce> list = provideProduceMapper.selectList(queryWrapper.eq("farmName",farmName));

        List<BusinessProduce> businessProduces = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            BusinessProduce businessProduce = new BusinessProduce();
            businessProduce.setPrice(list.get(i).getPrice());
            if(!list.get(i).getFruitId().equals("")) {
                businessProduce.setProductId(list.get(i).getFruitId());
                Fruit fruit =fruitMapper.selectById(list.get(i).getFruitId());
                System.out.println(fruit);
                businessProduce.setProductName(fruit.getFruitName());
            }
            else {
                businessProduce.setProductId(list.get(i).getVegetableId());
                Vegetable vegetable = vegetableMapper.selectById(list.get(i).getVegetableId());
                System.out.println(vegetable);
                businessProduce.setProductName(vegetable.getVegetableName());
            }



            businessProduces.add(businessProduce);
        }

        return CommonResponse.createForSuccess(businessProduces);
    }
}
